<template>
    <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#f3e7e9] to-[#e3eeff]">
        <div class="relative w-[650px] h-[415px] bg-white rounded-lg shadow-md">
            <!-- Form Box -->
            <div ref="formBox"
                class="absolute -top-[10%] left-[5%] w-[320px] h-[500px] bg-[#d3b7d8] rounded-lg shadow-md flex items-center justify-center z-10 transition-transform duration-500 ease-in-out">
                <!-- Register Form -->
                <div ref="registerBox" class="hidden hiddens w-full flex flex-col items-center">
                    <h1 class="mb-6 text-white uppercase tracking-[5px]">register</h1>
                    <input type="text" placeholder="用户名" v-model="formdata.username" @blur="validateUsername"
                        class="w-[70%] bg-transparent text-white border-b border-white/40 py-2.5 px-0 indent-2.5 my-2 text-sm tracking-wider focus:outline-none focus:border-[#a262ad80] focus:text-[#a262ad] transition-colors placeholder:text-white focus:placeholder:opacity-0" />
                    <p v-if="errors.username" class="w-[70%] text-xs text-red-500">{{ errors.username }}</p>

                    <input type="email" placeholder="邮箱" v-model="formdata.email" @blur="validateEmail"
                        class="w-[70%] bg-transparent text-white border-b border-white/40 py-2.5 px-0 indent-2.5 my-2 text-sm tracking-wider focus:outline-none focus:border-[#a262ad80] focus:text-[#a262ad] transition-colors placeholder:text-white focus:placeholder:opacity-0" />
                    <p v-if="errors.email" class="w-[70%] text-xs text-red-500">{{ errors.email }}</p>

                    <div class="flex flex-col w-[70%]">
                        <div class="flex gap-2">
                            <input type="text" placeholder="验证码" v-model="formdata.code" @blur="validateCode"
                                class="flex-1 bg-transparent text-white border-b border-white/40 py-2.5 px-0 indent-2.5 text-sm tracking-wider focus:outline-none focus:border-[#a262ad80] focus:text-[#a262ad] transition-colors placeholder:text-white focus:placeholder:opacity-0" />
                            <button :disabled="countdown > 0" @click="sendCode"
                                class="min-w-[80px] px-3 py-1.5 text-[#a262ad] border border-[#a262ad] rounded-md hover:bg-[#a262ad] hover:text-white transition-colors disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-300 disabled:cursor-not-allowed">
                                {{ countdown > 0 ? countdown : "发送" }}
                            </button>
                        </div>
                        <p v-if="errors.code" class="text-xs text-red-500 mt-1">{{ errors.code }}</p>
                    </div>

                    <input type="password" placeholder="密码" v-model="formdata.password" @blur="validatePassword"
                        class="w-[70%] bg-transparent text-white border-b border-white/40 py-2.5 px-0 indent-2.5 my-2 text-sm tracking-wider focus:outline-none focus:border-[#a262ad80] focus:text-[#a262ad] transition-colors placeholder:text-white focus:placeholder:opacity-0" />
                    <p v-if="errors.password" class="w-[70%] text-xs text-red-500">{{ errors.password }}</p>

                    <button @click="zhuce" v-loading="zhuceloading"
                        class="w-[70%] mt-4 bg-[#f6f6f6] rounded-lg py-3 text-[#a262ad] tracking-wider border-none cursor-pointer hover:bg-[#a262ad] hover:text-[#f6f6f6] transition-colors">
                        注册
                    </button>
                </div>

                <!-- Login Form -->
                <div ref="loginBox" class="w-full flex flex-col items-center">
                    <h1 class="mb-6 text-white uppercase tracking-[5px]">login</h1>
                    <input type="text" placeholder="用户名" v-model="loginData.username"
                        class="w-[70%] bg-transparent text-white border-b border-white/40 py-2.5 px-0 indent-2.5 my-2 text-sm tracking-wider focus:outline-none focus:border-[#a262ad80] focus:text-[#a262ad] transition-colors placeholder:text-white focus:placeholder:opacity-0" />

                    <input type="password" placeholder="密码" v-model="loginData.password"
                        class="w-[70%] bg-transparent text-white border-b border-white/40 py-2.5 px-0 indent-2.5 my-2 text-sm tracking-wider focus:outline-none focus:border-[#a262ad80] focus:text-[#a262ad] transition-colors placeholder:text-white focus:placeholder:opacity-0" />

                    <div class="w-[70%] text-right my-1">
                        <a @click="showResetPassword" class="text-white text-xs hover:text-[#a262ad] cursor-pointer">
                            忘记密码？
                        </a>
                    </div>

                    <button @click="login" v-loading="loginloading"
                        class="w-[70%] mt-4 bg-[#f6f6f6] rounded-lg py-3 text-[#a262ad] tracking-wider border-none cursor-pointer hover:bg-[#a262ad] hover:text-[#f6f6f6] transition-colors">
                        登录
                    </button>
                </div>
            </div>

            <!-- Side panels -->
            <div class="absolute left-[-2%] top-1/2 -translate-y-1/2 w-1/2 flex flex-col items-center">
                <p class="text-sm tracking-wider text-[#8e9aaf]">已有账号</p>
                <button @click="showLogin"
                    class="mt-3 px-4 py-2 bg-white text-[#a262ad] border border-[#d3b7d8] rounded-md hover:bg-[#d3b7d8] hover:text-white transition-colors">
                    去登录
                </button>
            </div>

            <div class="absolute right-[-2%] top-1/2 -translate-y-1/2 w-1/2 flex flex-col items-center">
                <p class="text-sm tracking-wider text-[#8e9aaf]">没有账号？</p>
                <button @click="showRegister"
                    class="mt-3 px-4 py-2 bg-white text-[#a262ad] border border-[#d3b7d8] rounded-md hover:bg-[#d3b7d8] hover:text-white transition-colors">
                    去注册
                </button>
            </div>
        </div>
    </div>

    <!-- Reset Password Dialog -->
    <el-dialog v-model="resetPasswordVisible" title="重置密码" width="400px" :close-on-click-modal="false"
        class="reset-dialog">
        <div class="flex flex-col items-center w-full">
            <div class="w-full mb-4">
                <input type="email" v-model="resetForm.email" placeholder="邮箱" @blur="validateResetEmail"
                    class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:border-[#a262ad] text-gray-600" />
                <p v-if="resetErrors.email" class="mt-1 text-xs text-red-500">{{ resetErrors.email }}</p>
            </div>

            <div class="w-full mb-4">
                <div class="flex gap-2">
                    <input type="text" placeholder="验证码" v-model="resetForm.code"
                        class="flex-1 px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:border-[#a262ad] text-gray-600" />
                    <button :disabled="resetCountdown > 0" @click="sendResetCode"
                        class="px-4 py-2 border border-[#a262ad] text-[#a262ad] rounded-md hover:bg-[#a262ad] hover:text-white transition-colors disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-300 disabled:cursor-not-allowed min-w-[100px]">
                        {{ resetCountdown > 0 ? `${resetCountdown}` : "发送" }}
                    </button>
                </div>
                <p v-if="resetErrors.code" class="mt-1 text-xs text-red-500">{{ resetErrors.code }}</p>
            </div>

            <div class="w-full mb-4">
                <input type="password" v-model="resetForm.newPassword" placeholder="新密码" @blur="validateResetPassword"
                    class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:border-[#a262ad] text-gray-600" />
                <p v-if="resetErrors.password" class="mt-1 text-xs text-red-500">{{ resetErrors.password }}</p>
            </div>
        </div>

        <template #footer>
            <div class="flex justify-end gap-2">
                <button @click="resetPasswordVisible = false"
                    class="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button @click="submitResetPassword" :disabled="resetLoading"
                    class="px-4 py-2 bg-[#a262ad] text-white rounded-md hover:bg-[#915999] transition-colors disabled:bg-gray-300">
                    确认
                </button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
definePageMeta({
    showInMenu: false,
    requiresAuth: false,
    layout: 'login',
})
import { useUserStore } from '~/stores/user'
// 登录注册相关的响应式变量
const router = useRouter()
const loginloading = ref(false)
const zhuceloading = ref(false)
const formdata = reactive({
    username: "",
    email: "",
    code: "",
    password: "",
})
const loginData = reactive({
    username: "",
    password: "",
})

const errors = reactive({
    username: "",
    password: "",
    email: "",
    code: ""  // Add this line
})

// 重置密码相关的响应式变量
const resetPasswordVisible = ref(false)
const resetLoading = ref(false)
const resetForm = reactive({
    email: '',
    code: '',
    newPassword: ''
})

const resetErrors = reactive({
    email: '',
    password: '',
    code: ''
})

// 统一的表单验证规则
const validationRules = {
    username: {
        pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]{3,8}$/,
        message: "用户名需为3~8个字符，允许汉字、字母、数字和下划线"
    },
    password: {
        pattern: /^(?=.*[a-zA-Z])(?=.*[0-9@#$%&]).{8,12}$/,
        message: "密码需为8~12个字符，至少包含字母和数字或特殊符号"
    },
    email: {
        pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
        message: "请输入有效的邮箱地址"
    },
    code: {
        pattern: /^\d{6}$/,
        message: "请输入6位数字验证码"
    }
}

// 通用验证函数
const validate = (field, value, errors) => {
    const rule = validationRules[field]
    if (!rule.pattern.test(value)) {
        errors[field] = rule.message
        return false
    }
    errors[field] = ""
    return true
}

// 验证方法
const validateCode = () => validate('code', formdata.code, errors)
const validateUsername = () => validate('username', formdata.username, errors)
const validateEmail = () => validate('email', formdata.email, errors)
const validatePassword = () => validate('password', formdata.password, errors)
const validateResetCode = () => validate('code', resetForm.code, resetErrors)
const validateResetEmail = () => validate('email', resetForm.email, resetErrors)
const validateResetPassword = () => validate('password', resetForm.newPassword, resetErrors)

// 使用倒计时
const {
    count: countdown,
    startCountdown,
    stopCountdown
} = useCountdown()

const {
    count: resetCountdown,
    startCountdown: startResetCountdown,
    stopCountdown: stopResetCountdown
} = useCountdown()

// 通用发送验证码函数
const sendEmailCode = async (options) => {
    const {
        email,
        validateFn,
        errors,
        startCount,
        stopCount,
        url,
        withToken = false,
        useFormData = false
    } = options

    if (!email) {
        errors.email = "请先填写邮箱"
        return
    }

    if (!validateFn()) return

    startCount()

    try {
        const body = useFormData ? (() => {
            const formData = new FormData()
            formData.append('email', email)
            return formData
        })() : { userAccount: email }

        const response = await customFetch(url, {
            method: 'POST',
            withToken,
            body
        })

        const successMessage = response.data || response.desc
        if (successMessage === '发送成功') {
            $message(successMessage, 'success')
        } else {
            $message(successMessage, 'warning')
            stopCount()
        }
    } catch (error) {
        $message('发送失败，请重试', 'error')
        stopCount()
    }
}

// 发送验证码方法
const sendCode = () => sendEmailCode({
    email: formdata.email,
    validateFn: validateEmail,
    errors,
    startCount: startCountdown,
    stopCount: stopCountdown,
    url: '/api/user/sendEmailCode',
    useFormData: true
})

const sendResetCode = () => sendEmailCode({
    email: resetForm.email,
    validateFn: validateResetEmail,
    errors: resetErrors,
    startCount: startResetCountdown,
    stopCount: stopResetCountdown,
    url: '/api/user/sendEmailCodeByUpdate',
    withToken: false
})

// 注册提交
const zhuce = async () => {
    validateUsername()
    validatePassword()
    validateCode()
    validateEmail()
    if (!errors.username && !errors.password && !errors.email && !errors.code) {
        try {
            zhuceloading.value = true
            const { data } = await customFetch('/api/user/userRegistration', {
                method: 'POST',
                body: {
                    userAccount: formdata.email,
                    emailCode: formdata.code,
                    userPasswd: formdata.password,
                    userName: formdata.username
                }
            })
            if (data == '注册成功') {
                $message(data, 'success')
                showLogin()
            } else {
                $message(data, 'warning')
            }
        } catch (error) {
            $message('注册失败，请重试', 'error')
        } finally {
            zhuceloading.value = false
        }
    }
}

// 登录提交
const login = async () => {
    try {
        loginloading.value = true
        const response = await customFetch('/api/user/user_login', {
            method: 'POST',
            withToken: false,
            body: {
                account: loginData.username,
                password: loginData.password
            }
        })
        if (response.code != 100) {
            $message(response.desc, 'warning')
            return
        }
        $message('登录成功', 'success')
        const token = useCookie('X-Auth-Token', {
            maxAge: 60 * 60 * 24,
            path: '/',
            secure: process.env.NODE_ENV === 'production', // 仅在生产环境启用
            sameSite: 'lax', // 改用 lax 而不是 strict
        })
        token.value = response.data.token
        const UserStore = useUserStore()
        UserStore.token = response.data.token
        router.replace('/User')
    } catch (error) {
        console.log(error)
        $message('登录失败，请重试', 'error')
    } finally {
        loginloading.value = false
    }
}

// 重置密码相关方法
const showResetPassword = () => {
    resetPasswordVisible.value = true
}

// 提交重置密码
const submitResetPassword = async () => {
    validateResetEmail()
    validateResetPassword()
    validateResetCode()
    if (!resetErrors.email && !resetErrors.password && !resetErrors.code) {
        try {
            resetLoading.value = true
            const response = await customFetch('/api/user/updatePasswordByCode', {
                method: 'POST',
                body: {
                    userAccount: resetForm.email,
                    emailCode: resetForm.code,
                    userPasswd: resetForm.newPassword
                }
            })
            if (response.data === '修改成功') {
                $message(response.data, 'success')
                resetPasswordVisible.value = false
                Object.assign(resetForm, {
                    email: '',
                    code: '',
                    newPassword: ''
                })
            } else {
                $message(response.data, 'warning')
            }
        } catch (error) {
            $message('重置失败，请重试', 'error')
        } finally {
            resetLoading.value = false
        }
    }
}

// DOM 操作相关
const formBox = ref(null)
const registerBox = ref(null)
const loginBox = ref(null)

const showRegister = () => {
    formBox.value.style.transform = 'translateX(80%)'
    loginBox.value.classList.add('hidden')
    registerBox.value.classList.remove('hidden')
}

const showLogin = () => {
    formBox.value.style.transform = 'translateX(0%)'
    registerBox.value.classList.add('hidden')
    loginBox.value.classList.remove('hidden')
}

</script>

<style scoped lang="scss">
/* 基础样式 */
.hiddens {
    transition: 0.5s;
}

/* 组件样式 */
:deep(.reset-dialog) {
    .el-dialog {
        &__header {
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e5e7eb;
        }

        &__title {
            font-size: 1.125rem;
            font-weight: 500;
            color: #374151;
        }

        &__body {
            padding: 1.5rem;
        }

        &__footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid #e5e7eb;
        }
    }
}

/* 表单元素样式 */
input {
    transition: all 0.3s ease-in-out;

    &:focus::placeholder {
        opacity: 0;
        transform: translateY(-0.5rem);
    }
}

button {
    transition: all 0.3s ease-in-out;

    &:disabled {
        cursor: not-allowed;
        opacity: 0.5;
    }
}

.form-box {
    transition: transform 0.5s ease-in-out;
}

.error {
    transition: all 0.3s ease-in-out;
}

/* 滚动条样式 */
::-webkit-scrollbar {
    width: 0.5rem;

    &-track {
        background-color: #f3f4f6;
        border-radius: 9999px;
    }

    &-thumb {
        background-color: #d3b7d8;
        border-radius: 9999px;

        &:hover {
            background-color: #a262ad;
        }
    }
}

/* 响应式设计 */
@media (max-width: 640px) {
    .container {
        width: 90%;
        margin-left: auto;
        margin-right: auto;
    }

    .form-box {
        width: 100%;
        left: 0;
    }

    .side-panel {
        display: none;
    }
}

/* 深色模式 */
@media (prefers-color-scheme: dark) {
    .container {
        background-color: #1f2937;
    }

    input {
        background-color: #374151;
        color: white;
    }

    .reset-dialog {
        background-color: #1f2937;
        color: white;
    }
}

/* 无障碍支持 */
@media (prefers-reduced-motion: reduce) {
    * {
        transition: none !important;
        animation: none !important;
    }
}

/* 打印样式 */
@media print {
    .container {
        box-shadow: none;
    }

    button {
        display: none;
    }
}
</style>
